<template>
  <div class="pad-out-box">
    <div v-for="(item, index) in tableData" :key="index">
      <div class="font-weight-600 font-size-18 padding-top-20 padding-bottom-10">{{ item.year }}</div>
      <el-table :border="true" :data="item.billItemList">
        <el-table-column align="center" label="账单周期" prop="kjine">
          <template slot-scope="scope">
            <span>{{ scope.row.cycleStartTime | formatDateTime('YYYY-MM-DD') }}</span>
            <span class="padding-left-right-5">-</span>
            <span>{{ scope.row.cycleEndTime | formatDateTime('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="账单类型" prop="kjine">
          <template slot-scope="scope">
            <span>{{ billTypeList[scope.row.bizType] }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="付款截止日期" prop="kjine">
          <template slot-scope="scope">
            <span>{{ scope.row.paymentDeadline | formatDateTime('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="账单金额" prop="kjine">
          <template slot-scope="scope">
            <span>{{ scope.row.amountReceivable | fmoneyThousand }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实付金额" prop="kjine">
          <template slot-scope="scope">
            <span>{{ scope.row.amountReceived | fmoneyThousand }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="欠费金额" prop="kjine">
          <template slot-scope="scope">
            <span>{{ scope.row.qianfeiJine | fmoneyThousand }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" prop="remark">
          <template slot-scope="scope">
            <el-button type="text" @click="toInfo(scope.row, 'info')">详情</el-button>
            <el-button v-if="scope.row.paymentStatus != 1 && scope.row.paymentStatus != 2 && scope.row.paymentStatus != 4" type="text" @click="toInfo(scope.row, 'bill')">出账</el-button>
            <!-- <el-button type="text" @click="urgePay(scope.row)">催费</el-button> -->
            <!-- <el-button v-if="scope.row.paymentStatus != 0" type="text" @click="addPayRecord(scope.row)">添加付款记录</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <info ref="info" :isInfo="isInfo" :billObj="billObj" :recordList="recordList" :bill-type-list="billTypeList"></info>

    <!-- 选择操作 -->
    <el-dialog title="选择操作" :visible.sync="handleTypeDialog" width="50%" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="flex-center-all">
        <el-button type="primary" size="mini" @click="printPage">打印催费单</el-button>
        <el-button type="primary" size="mini" class="margin-left-right-50">邮箱催缴</el-button>
        <el-button type="primary" size="mini">短信催缴</el-button>
      </div>
    </el-dialog>

    <!-- 添加付款记录 -->
    <el-dialog title="添加付款记录" :visible.sync="payDialogShow" width="65%" :close-on-click-modal="false" :close-on-press-escape="false">
      <form-common :filed-list="recordFiledList" ref="applyForm"></form-common>
      <div class="flex margin-bottom-20">
        <p class="left-lable font-size-16 padding-left-right-10 margin-top-5 required font-weight-400 color-333333" style="width: 165px">审批文件</p>
        <uploadFile :is-multiple="false" :limit="10" filed-name="file" :max-size="20" accept-file-type=".xlsx,.xls,.csv,.png,.jpg,.Png,.Jpg,.mp4,.pdf" :file-list="fileList" @handleSuccess="handleSuccess" file-url-name="fileUrl" file-txt-name="fileTitle"> </uploadFile>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="payDialogShow = false" class="el-button-reset">取 消</el-button>
        <el-button type="primary" @click="confirmRecord">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { apiBillList, apiBillInfo, apiAddPayRecord, apiIncomePayRecord, apiConstant } from '../../../api/contract';
  import formCommon from '@g/components/form/formCommon.vue';
  import dayjs from 'dayjs';
  import Info from './info.vue';
  import uploadFile from '../../projectInfo/modules/upload.vue';
  import { recordFiledList } from './form.js';
  import { accSubtr } from '@/common/js/utils.js';
  import { requestTips } from '../../../assets/util';

  export default {
    data() {
      return {
        tableData: [],
        currentBill: {},
        currentPage: 1,
        handleTypeDialog: false,
        payDialogShow: false,
        recordFiledList: recordFiledList,
        fileList: [],
        isInfo: false,
        billObj: {},
        recordList: [],
        billTypeList: {},
      };
    },

    mounted() {
      this.getConstant();
      this.getTableData();
    },

    methods: {
      // 账单类型
      async getConstant(){
        let res = await apiConstant();
        res.billType.forEach(item => {
          this.$set(this.billTypeList,item.key,item.value);
        })
      },
      //数据源
      async getTableData() {
        let res = await apiBillList({
          contractKey: this.$route.query.contractKey
        });
        res.billList.forEach(con => {
          con.billItemList.forEach(item => {
            let qianfeiJine = accSubtr(Number(item.amountReceivable), Number(item.amountReceived));
            qianfeiJine = Number(qianfeiJine)
            item.qianfeiJine = qianfeiJine < 0 ? 0 : qianfeiJine.toFixed(2);
            item.amountReceivable = item.amountReceivable.toFixed(2)
            item.amountReceived = item.amountReceived.toFixed(2)
          });
        });
        this.tableData = res.billList;
      },
      //分年
      splitData(data) {
        data.forEach(item => {
          let date = dayjs(item.jiezhiriqi).format('YYYY-MM-DD');
          item.year = date.split('-')[0];
        });

        let yearList = [];
        data.forEach(item => {
          if (yearList.indexOf(item.year) < 0) {
            yearList.push(item.year);
            this.tableData.push({
              year: item.year,
              list: [],
            });
          }
        });

        data.forEach(item => {
          this.tableData.forEach(con => {
            if (item.year == con.year) {
              con.list.push(item);
            }
          });
        });
      },

      //详情
      async toInfo(row, type) {
        this.isInfo = type == 'info' ? true : false;
        this.recordList = []
        this.billObj = {}
        this.getBillInfo(row);
        this.getPayRecord(row);
        this.$refs.info.dialogShow = true;
      },
      //账单详情
      async getBillInfo(row) {
        let res = await apiBillInfo({
          billKey: row.primaryKey,
        });
        res.billItemList.forEach(item => {
          let qianfeiJine = accSubtr(Number(item.amountReceivable), Number(item.amountReceived));
          item.weifujine = qianfeiJine < 0 ? 0 : qianfeiJine;
        });
        this.billObj = res;
      },
      //收入类合同（才有账单）付款记录
      async getPayRecord(row) {
        let res = await apiIncomePayRecord({ billKey: row.primaryKey });
        this.recordList = res.rows || []
      },
      //催费
      urgePay(row) {
        this.handleTypeDialog = true;
      },
      //添加付款记录
      addPayRecord(row) {
        this.currentBill = row;
        this.payDialogShow = true;
        this.$nextTick(() => {
          this.$refs.applyForm.clearValidateForm();
        });
      },
      //打印催费单
      printPage() {
        let pathUrl = {
          name: 'urge-bill',
          query: this.$route.query,
        };
        let { href } = this.$router.resolve(pathUrl);
        window.open(href);
      },
      //新增付款记录
      async confirmRecord() {
        let model = this.$refs.applyForm.validateForm();
        if (!model) return
        model.billKey = this.currentBill.primaryKey;
        model.attachmentList = this.fileList;
        model.contractKey = this.$route.query.contractKey
        model.contractCode = this.$route.query.contractCode
        model.fundsType = 1 //(1,收款 2,付款)
        if (this.fileList.length == 0) {
          this.$message.warning('请上传凭证');
          return;
        }
        let res = await apiAddPayRecord(model);
        requestTips(res, () => {
          this.payDialogShow = false;
        });
      },
      //上传成功
      handleSuccess(file, fileList) {
        if (file.data.rows && file.data.rows.length > 0) {
          this.fileList.push({
            fileId: file.data.rows[0].key,
            fileUrl: file.data.rows[0].url,
            fileTitle: file.data.rows[0].originalName,
            fileDesc: file.data.rows[0].originalName,
          });
        } else {
          this.fileList = [];
          this.$message.error(file.data.message);
        }
      },
    },

    components: { Info, uploadFile, formCommon },
  };
</script>
<style scoped></style>
